<template>
  <div class="dept">
    <basic-container>
      <div class="filter-container">
        <el-button-group>
          <el-button
            type="primary"
            v-if="deptManager_btn_add"
            icon="plus"
            @click="handlerAdd"
            >添加</el-button
          >
          <el-button
            type="primary"
            v-if="deptManager_btn_edit"
            icon="edit"
            @click="handlerEdit"
            >编辑</el-button
          >
          <el-button
            type="primary"
            v-if="deptManager_btn_del"
            icon="delete"
            @click="handleDelete"
            >删除</el-button
          >
        </el-button-group>
      </div>

      <el-row>
        <el-col :span="8" style="margin-top:15px;">
          <el-tree
            class="filter-tree"
            :data="treeData"
            node-key="id"
            highlight-current
            :props="defaultProps"
            :filter-node-method="filterNode"
            @node-click="getNodeData"
            default-expand-all
          ></el-tree>
        </el-col>
        <el-col :span="16" style="margin-top:15px;">
          <el-card class="box-card">
            <el-form
              :label-position="labelPosition"
              label-width="90px"
              :rules="rules"
              :model="form"
              ref="form"
            >
              <el-form-item label="父级节点" prop="parentId">
                <el-input
                  v-halfCharCode
                  v-model="form.parentId"
                  :disabled="formEdit"
                  placeholder="请输入父级节点"
                />
              </el-form-item>
              <el-form-item label="节点编号" prop="deptId" v-if="formEdit">
                <el-input
                  v-halfCharCode
                  v-model="form.deptId"
                  :disabled="formEdit"
                  placeholder="节点编号"
                />
              </el-form-item>
              <el-form-item label="部门名称" prop="name">
                <el-input
                  v-halfCharCode
                  v-model="form.name"
                  :disabled="formEdit"
                  placeholder="请输入名称"
                />
              </el-form-item>

              <el-form-item label="行政区域：" prop="delFlag">
                <el-input
                  v-halfCharCode
                  v-model="form.divisionName"
                  :disabled="formEdit"
                  placeholder="请输入名称"
                  v-if="formEdit"
                />
                <el-popover
                  placement="bottom"
                  width="400"
                  trigger="click"
                  v-model="delFlagVisibleArea"
                v-else
                >
                  <!-- <el-input
                    v-halfCharCode
                    placeholder="输入关键字进行过滤"
                    v-model="filterText"
                  /> -->

                  <el-tree
                    class="filter-tree"
                    :data="treeAreaData"
                    lazy
                    :load="loadNode"
                    :props="defaultAreaProps"
                    :filter-node-method="filterNode"
                    :expand-on-click-node="false"
                    @node-click="handleCheckChangeArea"
                    style="max-height:400px;overflow-y: auto;"
                    ref="tree"
                  ></el-tree>
                  <el-input
                    v-halfCharCode
                    slot="reference"
                    maxlength="30"
                    placeholder="请选择行政区域"
                    v-model="form.divisionName"
                    :disabled="formEdit"
                    :suffix-icon="
                      delFlagVisibleArea
                        ? 'el-icon-arrow-up'
                        : 'el-icon-arrow-down'
                    "
                    clearable
                  />
                </el-popover>
              </el-form-item>

              <el-form-item label="联系人" prop="username">
                <el-input
                  v-halfCharCode
                  v-model="form.username"
                  :disabled="formEdit"
                  placeholder="请输入联系人"
                />
              </el-form-item>
              <el-form-item label="手机号码" prop="phone">
                <el-input
                  v-halfCharCode
                  v-model="form.phone"
                  :disabled="formEdit"
                  placeholder="请输入手机号码"
                />
              </el-form-item>

              <el-form-item label="排序" prop="sort">
                <el-input
                  v-halfCharCode
                  type="number"
                  v-model="form.sort"
                  :disabled="formEdit"
                  placeholder="请输入排序"
                />
              </el-form-item>
              <el-form-item v-if="formStatus == 'update'">
                <el-button type="primary" @click="update">更新</el-button>
                <el-button @click="onCancel">取消</el-button>
              </el-form-item>
              <el-form-item v-if="formStatus == 'create'">
                <el-button type="primary" @click="create">保存</el-button>
                <el-button @click="onCancel">取消</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>
      </el-row>
    </basic-container>
  </div>
</template>

<script>
import { addObj, delObj, fetchTree, getObj, putObj } from '@/admin/api/dept';
import { mapGetters } from 'vuex';
let vm = null;
import { getdetails } from '@/admin/api/dept';
import { getDivision } from '@/admin/api/division';

var validatedeptname = (rule, value, callback) => {
  if (vm.currentDeptName && vm.currentDeptName === value) {
    callback();
  }
  getdetails(value).then((response) => {
    if (window.boxType === 'edit') callback();

    let result = response.data.data;

    if (result !== null) {
      callback(new Error('部门已经存在'));
    } else {
      callback();
    }
  });
};

let sortvalue = null;
var validatesort = (rule, value, callback) => {
  if (value != undefined) {
    callback();
  } else {
    callback(new Error('请选择排序值'));
  }
};

var phoneyanzheng = (rule, value, callback) => {
  if (value.length < 11) {
    callback(new Error('请输入11位的手机号码'));
  } else {
    if (value[0] != '1') {
      callback(new Error('请输入1开头的手机号码'));
    } else {
      callback();
    }
  }
};

export default {
  name: 'dept',
  data() {
    return {
      defaultAreaProps: {
        children: 'children',
        label: 'divisionName',
      },
      delFlagVisibleArea: false,
      //行政部门下拉框
      treeAreaData: [],
      list: null,
      total: null,
      formEdit: true,
      formAdd: true,
      formStatus: '',
      showElement: false,
      typeOptions: ['0', '1'],
      methodOptions: ['GET', 'POST', 'PUT', 'DELETE'],
      listQuery: {
        name: undefined,
      },
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'name',
      },
      rules: {
        parentId: [
          { required: true, message: '请输入父级节点', trigger: 'blur' },
        ],
        deptId: [
          { required: true, message: '请输入节点编号', trigger: 'blur' },
        ],
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { validator: validatedeptname, trigger: 'blur' },
        ],
        username: [
          { required: true, message: '请输入联系人', trigger: 'blur' },
        ],
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: phoneyanzheng, trigger: 'blur' },
        ],
        sort: [
          { required: false, message: '请确定排序值', trigger: 'blur' },
          { validator: validatesort, trigger: 'blur' },
        ],
      },
      labelPosition: 'right',
      form: {
        name: undefined,
        orderNum: undefined,
        parentId: undefined,
        divisionName:undefined,
        divisionCode:undefined,
        deptId: undefined,
        username: undefined,
        phone: undefined,
      },
      filterText: '',
      currentId: 0,
      deptManager_btn_add: false,
      deptManager_btn_edit: false,
      deptManager_btn_del: false,
      currentDeptName: '',
    };
  },
  created() {
    vm = this;
    this.getList();
    this.deptManager_btn_add = this.permissions['sys_dept_add'];
    this.deptManager_btn_edit = this.permissions['sys_dept_edit'];
    this.deptManager_btn_del = this.permissions['sys_dept_del'];
  },
  computed: {
    ...mapGetters(['elements', 'permissions']),
  },
  methods: {
    handleCheckChangeArea(data) {
      this.division = data.divisionCode;
      this.$set(this.form, 'divisionName', data.divisionName);
      this.$set(this.form, 'divisionCode', data.divisionCode);
      this.delFlagVisibleArea = false;
    },
    async loadNode(node, resolve) {
      let data = [];
      const response = await getDivision({
        lazy: true,
        parentId:node.data.divisionCode ?node.data.divisionCode : "000000",
      });
      data = response.data.data;
      resolve(data);
    },
    getList() {
      fetchTree(this.listQuery).then((response) => {
        this.treeData = response.data.data;
      });
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    getNodeData(data) {
      if (!this.formEdit) {
        this.formStatus = 'update';
      }
      getObj(data.id).then((response) => {
        this.form = response.data.data;
        this.currentDeptName = this.form.name;
      });
      this.currentId = data.id;
      this.showElement = true;
    },
    handlerEdit() {
      if (this.form.deptId) {
        this.formEdit = false;
        this.formStatus = 'update';
      }else{
        this.$message.warning("请先选择部门")
      }
    },
    handlerAdd() {
      this.resetForm();
      this.formEdit = false;
      this.formStatus = 'create';
    },
    handleDelete() {
      if(this.currentId){
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        delObj(this.currentId).then(() => {
          this.getList();
          this.resetForm();
          this.onCancel();
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000,
          });
        });
      });
      }else{
        this.$message.warning("请先选择部门")
      }
    },
    update() {
      this.$refs.form.validate((valid) => {
        if (!valid) return;
        putObj(this.form).then(() => {
          this.getList();
          this.$notify({
            title: '成功',
            message: '更新成功',
            type: 'success',
            duration: 2000,
          });
        });
      });
    },
    create() {
      this.$refs.form.validate((valid) => {
        if (!valid) return;
        addObj(this.form).then(() => {
          this.getList();
          this.$notify({
            title: '成功',
            message: '创建成功',
            type: 'success',
            duration: 2000,
          });
        });
      });
    },
    onCancel() {
      this.formEdit = true;
      this.formStatus = '';
    },
    resetForm() {
      this.form = {
        parentId: this.currentId,
      };
    },
  },
};
</script>

<style type="text/css" lang="scss" scoped>
.dept {
  .basic-container:first-child {
    padding-top: 32px;
  }
  /deep/ .el-card.is-always-shadow {
    box-shadow: none;
  }
  /deep/ .el-card {
    border: none;
  }
}
</style>
